﻿﻿﻿﻿require.config({
  paths: {
    'jquery': '/js/packages/jquery-2.14-min',
    'bootstrap': '/bootstrap/js/bootstrap.min',
    'moment':'/bootstrap/bootstrap-date-range/js/moment',
    'daterangepickerzn':'/bootstrap/bootstrap-date-range/js/daterangepicker.zh-CN',
    'bootstrapdaterange': '/bootstrap/bootstrap-date-range/js/daterangepicker'
  },
  shim: {
    'bootstrap': {
      deps: ['jquery'],
      exports: 'bootstrap'
    },
  	'moment':{
  		deps: ['jquery'],
        exports: 'bootstrap'
  	},
  	'bootstrapdaterange':{
  		deps: ['moment'],
        exports: 'bootstrap'
  	},
  	'daterangepickerzn':{
  		deps: ['moment'],
        exports: 'bootstrap'
  	}
  }
  
});
require(['jquery','bootstrap','bootstrapdaterange','moment','daterangepickerzn','bootstrapdaterange'], function ($) {


	$('.data-input').daterangepicker({
		 applyClass : 'btn-sm btn-success',
	        cancelClass : 'btn-sm btn-default',
	        locale: {
	            applyLabel: '确认',
	            cancelLabel: '取消',
	            fromLabel : '起始时间',
	            toLabel : '结束时间',
	            customRangeLabel : '自定义',
	            firstDay : 1
	        },
	        ranges : {
	            //'最近1小时': [moment().subtract('hours',1), moment()],
	            '今日': [moment().startOf('day'), moment()],
	            '昨日': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
	            '最近7日': [moment().subtract('days', 6), moment()],
	            '最近30日': [moment().subtract('days', 29), moment()],
	            '本月': [moment().startOf("month"),moment().endOf("month")],
	            '上个月': [moment().subtract(1,"month").startOf("month"),moment().subtract(1,"month").endOf("month")]
	        },
	        opens : 'right',    // 日期选择框的弹出位置
	        separator : ' to ',
	        showWeekNumbers : true,     // 是否显示第几周
	        format: 'YYYYMMDD'
	 
	    }, function(start, end, label) { // 格式化日期显示框
	        //$('#beginTime').val(start.format('YYYYMMDD'));
	        //$('#endTime').val(end.format('YYYYMMDD'));
	    	makeQuery();
	    })
	    .next().on('click', function(){
	    	
	        $(this).prev().focus();
	       
	    });
	
	var all_select = true
	$("li>label>input").on("change",function(argument){
		makeQuery();
	});
	$("section>div>div>input").on("input",function(argument){
		makeQuery();
	});
	$("#clear-query").click(function(){
		$("section>div>div>input").val("");
		makeQuery();
	});
	$("[data-toggle='popover']").popover();
	$('.tree li:has(ul)').addClass('parent_li').find(' > span').attr('title', 'Collapse this branch');
	var searchValue = "";
	$('#search-start').click(function(){
		search_wx();
	});
	$('#save-query').click(function(){
		saveQuery();
	});
	function search_wx() {
		var searchQ = $('textarea').val();
		$.ajax({
			url:'/search/wx',
		    type:'POST', //GET
		    async:true,    //或false,是否异步
		    data:{
		    	query:searchQ
		    },
		    dataType:'json',    //返回的数据格式：json/xml/html/script/jsonp/text
		    success:function(data,textStatus,jqXHR){
		    	window.location.href="/patents/patentslist.html";
		    	console.log(data)
		        console.log(textStatus)
		        console.log(jqXHR)
		    },
		    error:function(xhr,textStatus){
		        console.log('错误')
		        console.log(xhr)
		        console.log(textStatus)
		    },
		    complete:function(){
		        console.log('结束')
		    }
		});
	};
	function makeQuery() {
		var searchQ = searchQuery();
		var searchC = searchCon();
		if($('li>label>input:checked').length==122||searchC=='') {
			searchQ = searchQ
		}else {
			searchQ = searchQ+" AND ("+searchC+")"
		}
		
		$('#search-query')[0].innerHTML=searchQ;
		return searchQ;
	};
	function searchQuery(){
		var searchValue = "";
		$('.value').each(function(index){
			if($(this).val()!="") {
				if(searchValue==""){
		            searchValue=$(this).attr("data-name")+' = ("'+$(this).val()+'")';
				}else{
					searchValue=searchValue+" "+"AND"+" "+$(this).attr("data-name")+' = ("'+$(this).val()+'")';
				}
			}
		});
		$('.value-data').each(function(index){
			if($(this).val()!="") {
				if(searchValue==""){
		            searchValue=$(this).attr("data-name")+' = ["'+$(this).val()+'"]';
				}else{
					searchValue=searchValue+" "+"AND"+" "+$(this).attr("data-name")+' =["'+$(this).val()+'"]';
				}
			}
		});
		if(searchValue!="") {
			searchValue = searchValue;
		}
		return searchValue;
	};
	function saveQuery() {
		query = '';
		if($('#search-query')[0].innerHTML!='') {
			query = $('#search-query')[0].innerHTML;
		}else {
			query = makeQuery();
		}
		$.ajaxSetup({   
            async : false  
        }); 
		$.post('/search/query/save',
		{
			'query':query
		},
		function(data,status){
			alert('save ok!!')
		});
	};	
	function searchCon() {
		var searchValue = "";
		var curr_con = "";
		var s_con = "";
		var s_pt=[];
		$('ul.root>li>ul>li>label>input').each(function(index){
			if($(this).prop("checked") ==true){
				var pt = $(this).attr("data-pt");
				var co=$(this).parent('label').parent('li').parent('ul').parent('li').find('>label>input').attr('data-co');
				if(curr_con==''||curr_con==co) {
					curr_con = co
					s_pt.push(pt);
				}else {
					
					if(s_pt.length==3) {
						if(searchValue=='') {
							searchValue = 'co='+'("'+curr_con+'")'
						}else {
							searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")'
						}
					}else {
						ss_pt = ''
						for(var k in s_pt) {
							
							if(k==s_pt.length-1) {
								ss_pt = ss_pt+' "'+s_pt[k]+'"'
							}else {
								ss_pt = ss_pt+'"'+s_pt[k]+'" OR ';
							}
						}
						ss_pt = 'pt=('+ss_pt+')';
						if(searchValue=='') {
							searchValue = '('+'co='+'("'+curr_con+'")'+' AND '+ss_pt +')'
						}else {
							searchValue = searchValue+" OR ("+'co='+'("'+curr_con+'")'+' AND '+ss_pt +')'
						}
					}
					curr_con = co;
					s_pt = [];
					s_pt.push(pt);
				}
			}
		});
		
		if(s_pt.length==3) {
			if(searchValue=='') {
				searchValue = 'co='+'("'+curr_con+'")'
			}else {
				searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")'
			}
		}else if(s_pt.length!=0){
			ss_pt = ''
			for(var k in s_pt) {
				if(k==s_pt.length-1) {
					ss_pt = ss_pt+'"'+s_pt[k]+'"'
				}else {
					ss_pt = ss_pt+'"'+s_pt[k]+'" OR ';
				}
			}
			ss_pt = 'pt=('+ss_pt+')';
			if(searchValue=='') {
				searchValue = '('+'co='+'("'+curr_con+'")'+' AND '+ss_pt +')'
			}else {
				searchValue = searchValue+" OR ("+'co='+'("'+curr_con+'")'+' AND '+ss_pt +')'
			}
		}
		$('ul.sroot>li>label>input').each(function(index){
			if($(this).prop("checked") ==true){
				//searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")';
				curr_con = $(this).attr('data-co');
				if(searchValue=='') {
					searchValue = 'co='+'("'+curr_con+'")'
				}else {
					searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")'
				}
			}
		});
		
		$('ul.other-root>li>ul>li>label>input').each(function(index){
			if($(this).prop("checked") ==true){
				//searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")';
				curr_con = $(this).attr('data-co');
				if(searchValue=='') {
					searchValue = 'co='+'("'+curr_con+'")'
				}else {
					searchValue = searchValue+" OR "+'co='+'("'+curr_con+'")'
				}
			}
		});
		
		
		return searchValue;
	};

});
